<?php

namespace App\Services\WanSdk\ToApk;

use App\Commons\CommonConstant;
use App\Models\Games;
use App\Models\Users;
use App\Services\UserHutongService;
use App\Services\WanSdk\WanSdkToApkService;
use App\Structs\ToApkStruct;

// 我方H5sdk
// 根据公众号openid绑定官方账号
class H5Sdk extends SdkBase
{
    /**
     * 根据user获取转端链接
     * 有可能user注册时game_channel_id=1001，然后又跑到1002去玩并进行转端，那么此处下载的包应该为1002的包
     *
     * @param Users $user
     * @param integer $game_channel_id
     * @param integer $package_id
     * @return void
     */
    public function getUrls(Users $user, $game_channel_id)
    {
        $bind = UserHutongService::getInstance()->getOrCreateAccountBind($user->channel, $user->channel_openid);
        if (!$bind) {
            return;
        }

        // 把官方账号绑定到user
        $hutong = UserHutongService::getInstance()->getOrCreateHutong($user->user_id, $user->game_id, $user->channel, $user->channel_openid, $bind->account_openid);
        if (!$hutong) {
            return;
        }

        // 下载H5渠道微端apk的地址
        $urls = WanSdkToApkService::getInstance()->getDownloadUrlInfoByAccount($user->game_id, $game_channel_id, $bind->account_openid, $user->user_id);

        return $urls;
    }

    public function handle(ToApkStruct $struct)
    {
        $wx_openid = $struct->params['openid'];
        $package_id = $struct->params['package_id'] ?? 0;
        $game_id = $this->gameChannel['game_id'];
        $channel = $this->gameChannel['channel'];
        $game_channel_id = $this->gameChannel['id'];

        // 把自身user跟官方账号绑定
        $user = Users::whereRaw("channel_openid='{$wx_openid}' AND game_id={$game_id} AND channel={$channel}")->first();
        if ($user) {
            $urls = $this->getUrls($user, $game_channel_id);
        } else {
            // 不存在user，则直接获取下载包链接
            $urls = WanSdkToApkService::getInstance()->getDownloadUrlInfo($game_id, $game_channel_id);
        }

        // 如果是ios，并在默认浏览器打开了，则直接唤起游戏进行转端
        if ($struct->deviceType == CommonConstant::DEVICE_TYPE_IOS && $struct->isWechat === 0 && $struct->isPhone === 1) {
            return redirect()->away($urls['ios_url']);
        }

        $game = Games::where('game_id', $game_id)->first()->toArray();
        return view('h5_toapk.index', [
            'game'           => $game,
            'game_channel'   => $this->gameChannel,
            'query'          => $struct->params,
            'is_wechat'      => $struct->isWechat,
            'is_phone'       => $struct->isPhone,
            'device_type'    => $struct->deviceType,
            'ios_url'        => $urls['ios_url'],
            'android_url'    => $urls['android_url'],
            'quick_download' => $user?0:1,
        ]);
    }
}
